package de.pa2.proxy;

import java.io.IOException;

import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
import org.apache.http.HttpServerConnection;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ProxyThread extends Thread {
	private static Logger LOG = LoggerFactory.getLogger(ProxyThread.class);
	private final HttpService httpservice;
	private final HttpServerConnection inconn;

	public ProxyThread(final HttpService httpservice,
			final HttpServerConnection inconn) {
		super();
		this.httpservice = httpservice;
		this.inconn = inconn;
	}

	public void run() {
		LOG.debug("run: " + "New connection thread");
		HttpContext context = new BasicHttpContext(null);

		// Bind connection objects to the execution context
		context.setAttribute(Constants.HTTP_IN_CONN, this.inconn);
		try {
			while (!Thread.interrupted()) {
				if (!this.inconn.isOpen()) {
					DefaultHttpClientConnection outconn = (DefaultHttpClientConnection) context
							.getAttribute(Constants.HTTP_OUT_CONN);
					outconn.close();
					break;
				}

				this.httpservice.handleRequest(this.inconn, context);

				Boolean keepalive = (Boolean) context
						.getAttribute(Constants.HTTP_CONN_KEEPALIVE);
				if (!Boolean.TRUE.equals(keepalive)) {
					DefaultHttpClientConnection outconn = (DefaultHttpClientConnection) context
							.getAttribute(Constants.HTTP_OUT_CONN);
					outconn.close();
					this.inconn.close();
					break;
				}
			}
		} catch (ConnectionClosedException ex) {
			LOG.error("Client closed connection", ex);
		} catch (IOException ex) {
			LOG.error("I/O error: " + ex.getMessage(), ex);
		} catch (HttpException ex) {
			LOG.error("Unrecoverable HTTP protocol violation: "
					+ ex.getMessage(), ex);
		} finally {
			try {
				this.inconn.shutdown();
			} catch (IOException ignore) {
			}
			try {

				DefaultHttpClientConnection outconn = (DefaultHttpClientConnection) context
						.getAttribute(Constants.HTTP_OUT_CONN);
				if (outconn!=null)
				{
					outconn.shutdown();
					LOG.debug("outconn!=null");
				}
				else
				{
					LOG.debug("outconn==null");
				}

				// outconn.shutdown();
			} catch (IOException ignore) {
			}
		}
	}
}
